<template>
	<view class="wrapper page-top-bg">
		<view id="header" class="header">
			<index-header :page="pageData?.page || {}"></index-header>
		</view>
		<view class="container" :style="{paddingTop: `${paddingTop}px`}">
			<view v-if="setStore?.indexMode === 1">
				<!--轮播图 -->
				<view class="banner">
					<swiper
						class="swiper"
						circular
						indicator-active-color="#e3230e"
						indicator-dots
						autoplay>
						<swiper-item v-for="item in bannerList" :key="item.id">
							<view class="swiper-item" @click="clickBanner(item)">
								<image class="swiper-item-img" mode="aspectFill" :src="item.img"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<!--通知-->
				<view class="notice" v-if="noticeData?.noticeTitle">
					<uni-notice-bar
						show-icon 
						scrollable
						background-color="#ffffff"
						color="#333333"
						@click="clickNotice"
						:text="noticeData.noticeTitle" />
				</view>
			</view>
			<view class="container-box" v-else-if="setStore?.indexMode === 2">
				
				<view class="seckill" v-if="seckillList.length > 0">
					<view class="seckill-top">
						<text class="seckill-top-text">限时秒杀 💥 闪电特惠</text>
					</view>
					<view class="seckill-bottom">
						<swiper
							class="seckill-swiper"
							:style="{ height:  seckillProductHeight ? `${seckillProductHeight}px` : '100%' }"
							vertical
							circular
							autoplay>
							<swiper-item v-for="item in seckillList" :key="item.id">
								<view class="seckill-swiper-item main-flex">
									<view class="seckill-product" v-for="(product, index) in item" :key="index" @click="goSeckill">
										<goods-item-seckill :mode="2" :goods="product" :column="3"></goods-item-seckill>
									</view>
								</view>
							</swiper-item>
						</swiper>
					</view>
				</view>
				<diy
					style="position: relative;"
					@chooseGoods="chooseGoods"
					:diyItems="pageData.items">
				</diy>
			</view>
			<!--选择模式-->
			<view class="mode main-flex" v-if="setStore?.indexMode === 1">
				<view class="mode-item" @click="changeMode(1)">
					<view class="mode-item-icon">
						<image class="mode-item-icon-img" mode="aspectFit" src="/static/images/home/mode1.png"></image>
					</view>
					<view class="mode-item-name">配送到家</view>
				</view>
				<view class="mode-item" @click="changeMode(2)">
					<view class="mode-item-icon">
						<image class="mode-item-icon-img" mode="aspectFit" src="/static/images/home/mode2.png"></image>
					</view>
					<view class="mode-item-name">门店自提</view>
				</view>
			</view>
			
			<view class="title">
				<u-divider text="廷与严选" textColor="#333333" lineColor="#c8c7cc"></u-divider>
			</view>
			<view class="goods1" id="indexGoods">
				<u-waterfall v-model="productList" columns="3">
					<template v-slot:column="{colList, colIndex}">
						<view class="goods1-box" v-for="(item, index) in colList" :key="index">
							<goods-item @chooseGoods="chooseGoods" :goods="item"></goods-item>
						</view>
					</template>
				</u-waterfall>
			</view>
			
			<!--加载-->
			<view
				v-if="isNull"
				class="null main-flex">
				<u-empty text="商品为空" icon="/static/images/null.png"></u-empty>
			</view>
			<view
				v-else
				class="more main-flex">
				<uni-load-more :status="status" />
			</view>
		</view>
		<!--商品弹窗-->
		<goods-popup
		@close="closeGoods"
		:showGoods="showGoods"
		:goods="goodsInfo"></goods-popup>
		
		<!-- #ifdef MP-WEIXIN -->
		<!-- <uu-privacy manual id="uu-privacy" appName="测试" /> -->
		<!-- #endif -->
		
	</view>
</template>

<script setup>
import useSetStore from '@/store/modules/set'
import {
	allProvince,
	indexBanner,
	notice,
	shopMobilePage,
	spreadSubjectList,
	productSeckillList,
	indexLabel } from "@/api/app_api/index"
import { product } from "@/api/app_api/product"
import { getNode, chunkArray } from '@/utils/ty.js';
import { data } from '@/utils/data.js';
import { getCurrentInstance, nextTick, ref, watch, watchEffect } from 'vue';
import { onShow, onReady, onLoad, onReachBottom, onPullDownRefresh, onShareAppMessage } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import { share } from '@/utils/config'
import { couponReceiveList, couponProductReceiveList, couponGetOne } from "@/api/app_api/coupon"

	
	
	// 微信小程序配置：禁用样式隔离
	defineOptions({
	  options: {
	    styleIsolation: 'shared' // 关键配置
	  }
	})
	
	const { proxy }  = getCurrentInstance()
	const userStore = useUserStore()
	const setStore = useSetStore()
	
	// 页面设置
	const windowHeight = ref(0)
	const pageHeight = ref(0)
	const paddingTop = ref(0)
	const instance = getCurrentInstance()
	const init = async () => {
		// #ifdef MP-WEIXIN
		const height = uni.getWindowInfo().windowHeight
		// #endif
		// #ifndef MP-WEIXIN
		const height = uni.getSystemInfoSync().windowHeight
		// #endif
		const query = uni.createSelectorQuery()
		const node = await getNode(query, '#header')
		paddingTop.value = node?.height || 0
		windowHeight.value = height
		console.log(paddingTop.value)
		pageHeight.value = height - node.height
	}
	
	// 切换模式
	const changeMode = (mode) => {
		userStore.changeMode(mode)
	}
	
	// 获取轮播图
	const bannerList = ref([])
	const getBanner = () => {
		indexBanner().then(res => {
			bannerList.value = res?.data || []
		})
	}
	// 点击轮播图
	const clickBanner = (item) => {
		proxy.gotoPage(item.url)
	}
	
	// 查询通知
	const noticeData = ref({})
	const getNotice = () => {
		notice().then(res => {
			noticeData.value = res?.data || {}
		})
	}
	
	//查看通知
	const clickNotice = () => {
		uni.navigateTo({
			url: `/pages/notice/notice?id=${noticeData.value.noticeId}`
		})
	}
	
	// 获取首页diy配置
	const pageData = ref({})
	const getShopMobilePage = () => {
		shopMobilePage({
			pageCode: 1
		}).then(res => {
			if (res?.data?.pageDataJson) {
				pageData.value = res.data.pageDataJson
				nextTick(() => {
					init()
				})
			}
		})
	}
	
	// 获取秒杀商品
	const seckillList = ref([])
	const getSeckillList = () => {
		if (!userStore.regionCode || !userStore.sellChannel) return false
		productSeckillList({
			regionCode: userStore.regionCode,
			sellChannel: userStore.sellChannel
		}).then(res => {
			seckillList.value = res?.data || []
			seckillList.value = chunkArray(seckillList.value, 3)
			if (seckillList.value.length > 0) {
				nextTick(() => {
					getSeckillProductHeight()
				})
			}
		})
	}
	// 获取秒杀商品高度
	const seckillProductHeight = ref(0)
	const getSeckillProductHeight = async () => {
		const query = uni.createSelectorQuery()
		const node = await getNode(query, '.seckill-swiper-item')
		seckillProductHeight.value = node?.height || 0
	}
	
	// 获取主题
	const subjectList = ref([])
	const getSubjectList = () => {
		if (!userStore.regionCode) return false
		spreadSubjectList({
			regionCode: userStore.regionCode,
			sellChannel: userStore.sellChannel,
			status: 1
		}).then(res => {
			subjectList.value = res?.data || {}
		})
	}
	
	// 商品查询
	const productList = ref([])
	const pageNum = ref(1)
	const pageSize = ref(12)
	const total = ref(0)
	const isLoading = ref(false)
	const status = ref('loading')
	const isNull = ref(false)
	
	const searchFirst = () => {
		pageNum.value = 1
		productList.value = []
		if (!userStore.regionCode) return false
		getList()
	}
	
	const getList = () => {
		if (!userStore.regionCode || !userStore.sellChannel) return false
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			sellChannel: userStore.sellChannel,
			regionCode: userStore.regionCode,
			recommend: 1
		}
		isLoading.value = true
		// uni.showLoading({
		// 	title: '数据加载中...'
		// })
		product(params).then(res => {
			productList.value = pageNum.value === 1 ? res.data || [] : productList.value.concat(res.data || [])
			status.value = res.data.length === pageSize.value ? 'loading' : 'no-more'
			total.value = res.allNumber
			isNull.value = res.allNumber === 0 && pageNum.value === 1
			isLoading.value = false
			// uni.hideLoading()
		}).catch(() => {
			isLoading.value = false
			// uni.hideLoading()
		})
	}

	
	// 监听
	watch(() => userStore.token, (nval, oval) => {
		if (nval) {
			defaultFun()
		}
	})
	watch(() => userStore.regionCode, (newVal, oldVal) => {
		defaultFun()
	})
	watch(() => userStore.sellChannel, (newVal, oldVal) => {
		defaultFun()
	})
	
	onReachBottom(() => {
		if(status.value == 'no-more') return false;
		pageNum.value += 1
		status.value = 'loading'
		getList()
	})
	
	// 选择商品
	const showGoods = ref(false)
	const goodsInfo = ref({})
	const chooseGoods = (item) => {
		showGoods.value = true
		goodsInfo.value = item
	}
	const closeGoods = () => {
		showGoods.value = false
		goodsInfo.value = {}
	}
	
	// 前往秒杀
	const goSeckill = () => {
		uni.navigateTo({
			url: '/pages/seckill/seckill'
		})
	}
	
	onLoad((option) => {
		if (option.spreadCode) {
			setStore.spreadCode = option.spreadCode
		}
		if (option.isTc) {
			setStore.isTc = Number(option.isTc)
		}
		defaultFun()
	})
	
	onPullDownRefresh(() => {
		defaultFun()
		uni.stopPullDownRefresh()
	})
	
	onReady(() => {
		init()
	})
	onShow(() => {
		if (setStore.indexMode === 2) {
			getSeckillList()
		}
		uni.setTabBarStyle({
			backgroundColor: setStore.env === 'test' ? '#2c9af1' : '#ffffff'
		})
	})
	// #ifdef MP-WEIXIN
	onShareAppMessage(() => {
		return {
			title: share.title,
			path: `/pages/index/index?spreadCode=${userStore.user.spreadCode}&isTc=${userStore.isTc}`,
			imageUrl: share.img
		}
	})
	// #endif
	
	const defaultFun = () => {
		getBanner()
		getNotice()
		if (setStore.indexMode === 2) {
			getShopMobilePage()
			getSeckillList()
			getSubjectList()
		}
		searchFirst()
	}
	
	const clickTools = (type, e) => {
		if (type === 2) { // 选择商品
			chooseGoods(e)
		}
	}

</script>

<style lang="scss">
	.wrapper {
	}
	.container {
		// padding: 0 20rpx;
		.title {
			font-weight: 600;
		}
		&-box {
			padding: 0 20rpx;
		}
	}
	.header {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background: linear-gradient(to bottom, #e3230e, $bg-color) no-repeat; /* 蓝色渐变 */
		background-size: 100% 400rpx;
		z-index: 10;
	}
	.seckill {
		// background-color: #ffffff;
		padding: 10rpx 20rpx;
		&-top {
			color: #ffffff;
			text-align: center;
			&-text {
				font-size: 32rpx;
				font-weight: 600;
			}
		}
		&-bottom {
			margin: 10rpx -10rpx 0rpx;
		}
		&-title {
			position: relative;
			height: 80rpx;
			font-size: 30rpx;
			font-weight: 800;
			color: #ffffff;
			line-height: 68rpx;
			background-color: #e3230e;
			text-align: center;
			padding: 0 10rpx;
			border-radius: 20rpx 20rpx 0 0;
			&:before{
				content: '';
				position: absolute;
				width: 20rpx;
				height: 20rpx;
				bottom: 0;
				left: -20rpx;
				background: radial-gradient(circle at 0 0,
				      transparent 40rpx,
				      #e3230e 40rpx); 
			}
			&:after{
				content: '';
				position: absolute;
				width: 20rpx;
				height: 20rpx;
				bottom: 0;
				right: -20rpx;
				background: radial-gradient(circle at 20rpx 0,
				      transparent 20rpx,
				      #e3230e 20rpx); 
			}
		}
		&-swiper {
			width: 100%;
			height: 320rpx;
		}
		&-right {
			justify-content: flex-end;
			font-size: 28rpx;
			color: $text-dark;
			margin-right: 20rpx;
		}
		&-product {
			width: 33.333%;
			padding: 10rpx;
			box-sizing: border-box;
			&-column2 {
				width: 50%;
				padding: 10rpx;
				box-sizing: border-box;
			}
			&-column3 {
				width: 33.333%;
				padding: 10rpx;
				box-sizing: border-box;
			}
		}
	}
	.banner {
		width: 100%;
		height: 320rpx;
		border-radius: 10rpx;
		overflow: hidden;
		.swiper {
			width: 100%;
			height: 100%;
			&-item {
				width: 100%;
				height: 100%;
				&-img {
					width: 100%;
					height: 100%;
				}
			}
			.uni-swiper-dot {
				width: 8px;
				height: 8px;
				transition: all .3s;
			}
			.uni-swiper-dot-active {
				width: 16px !important;
				border-radius: 4px !important;
			}
		}
	}
	.notice {
		margin-top: 20rpx;
		&-icon {
			width: 24px;
			height: 24px;
			&-img {
				width: 100%;
				height: 100%;
			}
		}
		:deep(.uni-noticebar) {
			padding: 5px 10px;
			margin: 0;
			border-radius: 10rpx;
		}
		:deep(.uni-noticebar-icon) {
			color: #e3230e !important;
		}
	}
	.mode {
		justify-content: space-between;
		margin-top: 20rpx;
		padding: 0 20rpx;
		&-item {
			width: 345rpx;
			text-align: center;
			background-color: #ffffff;
			padding: 20rpx 0;
			border-radius: 10rpx;
			&-icon {
				&-img {
					width: 64rpx;
					height: 64rpx;
				}
			}
			&-name {
				font-size: 32rpx;
				font-weight: bold;
				margin-top: 10rpx;
			}
		}
	}
	.title {
		font-size: 30rpx;
		padding: 0 20rpx;
	}
	.goods1 {
		margin-top: 20rpx;
		padding: 0 20rpx;
		.goods1-box + .goods1-box {
			margin-top: 20rpx;
		}
	}
	:deep(.u-column) {
		&:not(:first-child) {
				margin-left: 20rpx !important;
		}
	}
</style>
